package downloader;

import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.SgmlPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Evgeniy Krasko
 * Date: 30.10.11
 * Time: 18:54
 */
public class HtmlUnitPageProvider implements PageProvider {
    public static final Logger logger = Logger.getLogger(HtmlUnitPageProvider.class.getName());
    public static final int SLEEP_TIME = 500;
    private static ThreadLocal<HtmlUnitPageProvider> providers = new ThreadLocal<HtmlUnitPageProvider>() {
        @Override
        public HtmlUnitPageProvider initialValue() {
            return new HtmlUnitPageProvider();
        }
    };

    private WebClient webClient;


    private HtmlUnitPageProvider() {
    }

    public static synchronized PageProvider getInstance() {
        return providers.get();
    }

    public SgmlPage getPage(String url) {
        return getPage(url, Collections.<String, String>emptyMap(), HttpMethod.GET);
    }

    public SgmlPage getPage(String url, Map<String, String> params, HttpMethod method) {
        try {
            try {
                Thread.sleep(SLEEP_TIME);
            } catch (InterruptedException e) {
                //do nothing
            }
            WebRequest request = new WebRequest(new URL(url), method);
            request.setCharset("UTF-8");
            List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                paramsList.add(new NameValuePair(key, params.get(key)));
            }
            request.setRequestParameters(paramsList);
            return webClient.getPage(request);
        } catch (MalformedURLException e) {
            logger.warning("URL " + url + " is not valid");
        } catch (IOException e) {
            logger.warning("Cannot download page with url " + url);
        }
        return null;
    }

    {
        final BeanFactory beanFactory = new ClassPathXmlApplicationContext("config/connect.xml");
        webClient = (WebClient) beanFactory.getBean("webClient");
        webClient.setJavaScriptEnabled(false);
        webClient.setCssEnabled(false);
        webClient.setAppletEnabled(false);
    }
}
